#include "lcd.h"
#include "ltdc.h"
#include "dma2d.h"

#ifdef __GNUC__
uint32_t fram[800 * 480] __attribute__((section(".sram0")));

#else
uint16_t fram[800 * 480] __attribute__((at(0xC0000000)));
#endif

void Lcd_CLear(uint16_t color)
{
  int i; // 计数变量

  while (LTDC->CDSR != 0X00000001); // 判断 显示状态寄存器LTDC_CDSR 的第0位 VDES：垂直数据使能显示状态，可以避免撕裂效应
  for (i = 0; i < (480 * 800); i++) {
    *(__IO uint16_t *)((uint32_t)fram + 2 * i) = color; // 写入显存
  }
}
void LCD_DrawPoint(uint16_t x, uint16_t y, uint32_t color)
{

  *(__IO uint16_t *)((uint32_t)fram + 2 * (800 * y + x)) = color;
}
void Dma2d_Fill(uint16_t sx, uint16_t sy, uint16_t ex, uint16_t ey, uint32_t color)
{
  uint32_t addr;
  uint32_t off = 0;
  addr         = (uint32_t)fram + 2 * (800 * sy + sx);
  off          = 800 - (ex - sx + 1);
  __HAL_RCC_DMA2D_CLK_ENABLE();
  DMA2D->CR &= ~DMA2D_CR_START;
  DMA2D->CR     = DMA2D_R2M;
  DMA2D->OPFCCR = LTDC_PIXEL_FORMAT_RGB565;
  DMA2D->OMAR   = addr;
  DMA2D->OOR    = off;
  DMA2D->NLR    = ((ex - sx + 1) << 16) | (ey - sy + 1);
  DMA2D->OCOLR  = color;
  DMA2D->CR |= DMA2D_CR_START;
  while ((DMA2D->ISR & DMA2D_FLAG_TC) == 0);
  DMA2D->IFCR |= DMA2D_FLAG_TC;
}
/*
^函数：填充指定区域颜色。
参数：
    sx：起始坐标x轴
    sy：起始坐标y轴
    ex：填充宽度
    ey：填充高度
color：填充颜色 ex与ey不能小于
*/
void Dma2d_Fill_color(uint16_t sx, uint16_t sy, uint16_t ex, uint16_t ey, uint32_t color)
{
  uint32_t addr;
  uint32_t off = 0;
  ex += sx;
  ey += sy;
  if (ey > 480 || ex > 800) {
    sx = 0;
    sy = 0;
  }
  addr = (uint32_t)fram + 2 * (800 * sy + sx);
  off  = 800 - (ex - sx + 1);
  __HAL_RCC_DMA2D_CLK_ENABLE();
  DMA2D->CR &= ~DMA2D_CR_START;
  DMA2D->CR     = DMA2D_R2M;
  DMA2D->OPFCCR = LTDC_PIXEL_FORMAT_RGB565;
  DMA2D->OMAR   = addr;
  DMA2D->OOR    = off;
  DMA2D->NLR    = ((ex - sx + 1) << 16) | (ey - sy + 1);
  DMA2D->OCOLR  = color;
  DMA2D->CR |= DMA2D_CR_START;
  while ((DMA2D->ISR & DMA2D_FLAG_TC) == 0);
  DMA2D->IFCR |= DMA2D_FLAG_TC;
}

void Dma2d_Fill_bmp(uint16_t sx, uint16_t sy, uint16_t ex, uint16_t ey, uint16_t *color)
{
  // ex-=1;
  // ey-=1;
  // ex+=sx;
  // 	ey+=sy;
  // 	if(ey>599||ex>1023){
  // 		 ex-=sx;
  // 	   ey-=sy;
  // 		  sx=0;
  // 	    sy=0;
  // 	}
  uint32_t addr;
  uint32_t off = 0;
  off          = 800 - (ex - sx + 1);
  addr         = (uint32_t)fram + 2 * (800 * sy + sx);
  __HAL_RCC_DMA2D_CLK_ENABLE();
  DMA2D->CR &= ~DMA2D_CR_START;              /* 先停止DMA2D */
  DMA2D->CR      = DMA2D_M2M;                /* 存储器到存储器模式 */
  DMA2D->FGPFCCR = LTDC_PIXEL_FORMAT_RGB565; /* 设置颜色格式 */
  DMA2D->FGMAR   = (uint32_t)color;
  DMA2D->OMAR    = addr;
  DMA2D->FGOR    = 0;
  DMA2D->OOR     = off;
  DMA2D->NLR     = ((ex - sx + 1) << 16) | (ey - sy + 1);
  DMA2D->CR |= DMA2D_CR_START;
  while ((DMA2D->ISR & DMA2D_FLAG_TC) == 0);
  DMA2D->IFCR |= DMA2D_FLAG_TC;
}